import json
import os
from enum import Enum


class NotificationType(Enum):
    """支持的通知类型枚举"""
    TRAY_BUBBLE = "系统托盘气泡"
    WINDOWS_TOAST = "Windows Toast通知"
    SOUND = "声音提醒"
    EMAIL = "邮件通知"
    DESKTOP_POPUP = "桌面弹窗"
    LOG_FILE = "日志文件记录"
    SYSTEM_LOG = "系统日志"
    LED_BLINK = "LED闪烁(硬件)"
    SMS = "短信通知"
    CUSTOM_SCRIPT = "自定义脚本执行"


class NotificationConfig:
    """通知配置管理器"""
    CONFIG_FILE = "notification_config.json"

    DEFAULT_CONFIG = {
        "enabled_methods": [
            NotificationType.TRAY_BUBBLE.value,
            NotificationType.WINDOWS_TOAST.value
        ],
        "sound_settings": {
            "enabled": True,
            "file_path": "alarm.wav"
        },
        "email_settings": {
            "enabled": False,
            "smtp_server": "smtp.example.com",
            "smtp_port": 587,
            "username": "your_email@example.com",
            "password": "",
            "recipient": "recipient@example.com"
        },
        "windows_toast": {
            "duration": 10,  # 显示秒数
            "with_sound": True
        },
        "desktop_popup": {
            "duration": 5,
            "position": "bottom-right"
        },
        "log_settings": {
            "file_path": "notifications.log"
        },
        "custom_script": {
            "path": "",
            "parameters": ""
        }
    }

    def __init__(self):
        self.config = self._load_config()

    def _load_config(self):
        """加载配置文件"""
        if os.path.exists(self.CONFIG_FILE):
            try:
                with open(self.CONFIG_FILE, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return self.DEFAULT_CONFIG
        return self.DEFAULT_CONFIG

    def save_config(self):
        """保存配置到文件"""
        with open(self.CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, indent=2, ensure_ascii=False)

    def is_method_enabled(self, method: NotificationType) -> bool:
        """检查通知方式是否启用"""
        return method.value in self.config["enabled_methods"]

    def get_setting(self, section, key, default=None):
        """获取特定配置项"""
        return self.config.get(section, {}).get(key, default)

    def update_setting(self, section, key, value):
        """更新配置项"""
        if section not in self.config:
            self.config[section] = {}
        self.config[section][key] = value
        self.save_config()

    def enable_method(self, method: NotificationType):
        """启用通知方式"""
        if method.value not in self.config["enabled_methods"]:
            self.config["enabled_methods"].append(method.value)
            self.save_config()

    def disable_method(self, method: NotificationType):
        """禁用通知方式"""
        if method.value in self.config["enabled_methods"]:
            self.config["enabled_methods"].remove(method.value)
            self.save_config()